package com.sfh.cp.mass.pst.impl;

import android.text.TextUtils;

import com.sfh.cp.mass.pst.IPstNote;
import com.sfh.cp.mass.req.ReqPageNote;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import crm.sfh.server.MangeNote;
import crm.sfh.server.MangerUser;
import crm.sfh.server.SNote;
import crm.sfh.server.entity.EContent;
import crm.sfh.server.entity.ENote;
import crm.sfh.server.entity.rsp.TPage;

/**
 * 功能描述:
 *
 * @date 2018/5/4
 */
public  class PstNote extends AbstractPresenter< IPstNote.IVNote> implements IPstNote{
    @Override
    public void listPage(final ReqPageNote req) {
        BmobQuery<SNote> query = new BmobQuery<>();
        HashMap<String, String> where = req.getWhere();
        if (where.size() > 0){
            Iterator<Map.Entry<String, String>> iterator = where.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                query.addWhereEqualTo(entry.getKey(), entry.getValue());
            }
        }

        // 根据score字段降序显示数据
        if (!TextUtils.isEmpty(req.getOrder())){
            query.order(req.getOrder());
        }
        query.setSkip((req.nowPage - 1) * 10);
        query.setLimit(req.nowPage * 10);
        query.include("author,fristMsg.author,twoMsg.author,threeMsg.author");
        query.findObjects(AppCacheManager.getApplication(), new FindListener<SNote>() {
            @Override
            public void onSuccess(List<SNote> list) {

                TPage<EContent> page = new TPage<>();
                page.setNowPage(req.nowPage);
                page.setTotalPage(list.size() >= 10 ? req.nowPage + 1 : req.nowPage);
                List<EContent> contents = new ArrayList<>(10);
                //更新阅览次数
                new MangeNote().updateReadSize(AppCacheManager.getApplication(), list);
                for (SNote note : list) {
                    EContent content = new EContent();
                    content.setContentType(note.getENote());
                    contents.add(content);
                }
                page.setList(contents);
                getView().onSuccess(page);
            }

            @Override
            public void onError(int i, String s) {
                getView().onError("未查询到数据");
            }
        });
    }

    @Override
    public void updateFabulous(ENote req) {
        new MangeNote().updateFabulous(AppCacheManager.getApplication(), req.getNoteId(),1, null);
        // 更新魅力+1
        new MangerUser().updateCharm(AppCacheManager.getApplication(),req.getAuthor().getUserId(), 1, null);


    }

}
